import {
  createRouter,
  createWebHistory,
  NavigationGuardNext,
  RouteLocationNormalized
} from 'vue-router'
import routes from './routes'
import { useUserStore } from '@/store/user/user'

// NProgress
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const router = createRouter({
  history: createWebHistory(),
  routes
})
let userStore: any | undefined = undefined
/**
 * Routing to intercept
 */
router.beforeEach(
  async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    if (!userStore) {
      userStore = useUserStore()
    }

    NProgress.start()
    next()

    NProgress.done()

    // 设置页面标题
    document.title = (to.meta.title as string) || import.meta.env.VITE_APP_TITLE
    if (!NProgress.isStarted()) {
      NProgress.start()
    }
    const token: String = userStore.getToken
    if (to.path === '/login') {
      userStore.setToken('')
      userStore.setUserInfo({})
    }
    if (!token && to.path !== '/login') {
      next({ path: '/login' })
    } else {
      next()
    }
  }
)

router.afterEach(() => {
  NProgress.done()
})

export default router
